<!--
 * @Author: 吴竹叶 2107206923@qq.com
 * @Date: 2023-10-07 14:34:01
 * @LastEditors: 胡威 3749920422@qq.com
 * @LastEditTime: 2024-02-28 13:45:57
 * @FilePath: \BZ_JT_AnQuanHuanBaoGuanLiApp\src\views\staging\commom\evaluate\components\safety\chart.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="bg-white p-2">
    <custom-timer type="year-month" title="评分时间：" :is-interval="false" :is-border="false" :date-value.sync="scoreTime" @change="()=>{CompanyAvgScore(); StatisticsPort();AvgMaxMinScorePort()}" />
    <customTitle :is-line="true" bg-color="#3795ff" title="集团企业平均得分" />
    <div class="mb-1">综合得分：<b style="color: #0bf9af;" class="mr-1">{{ scoreObj.avgScore }}</b>最低企业得分：<b style="color: #ffc200;" class="mr-1">{{ scoreObj.minScore }}</b>最高企业得分：<b style="color: #00aaff;">{{ scoreObj.maxScore }}</b></div>
    <div id="radarChart" ref="radarChart" style="height: 300px;" />
    <customTitle :is-line="true" bg-color="#3795ff" title="集团企业得分情况统计" />
    <div id="pieChart" ref="pieChart" style="height: 260px;text-align: center;" />
  </div>
</template>

<script>
import customTimer from '@/components/common/custom-timer.vue'
import { pieChart, radarChart } from '@/utils/chart'
import { currentTime } from '@/utils/dayJs'
import { pagePort } from './config.js'
import Highcharts from 'highcharts/highcharts'
import HighchartsMore from 'highcharts/highcharts-more'
import commonList from '@/assets/mixin/commonList'

HighchartsMore(Highcharts)
export default {
  components: {
    customTimer
  },
  mixins: [commonList],
  inject: ['layout'],
  data() {
    return {
      scoreTime: currentTime('年月'),
      scoreObj: {},
      radarChart: null
    }
  },
  computed: {
    configField() {
      return `${this.$route.query.current}`
    },
    getPort() {
      return pagePort[this.configField] ?? false
    }
  },
  mounted() {
    this.CompanyAvgScore()
    this.StatisticsPort()
    this.AvgMaxMinScorePort()
  },
  methods: {
    async CompanyAvgScore() {
      this.layout.showAreaLoading(['#radarChart'])
      const { status, data } = await this.getPort.CompanyAvgScore({
        scoreTime: this.scoreTime
      })
      if (status === 0 && data) {
        this.initRadarChart(data)
      }
      this.layout.hideAreaLoading(['#radarChart'])
    },
    initRadarChart(data) {
      const dataArr = []; const maxArr = []; const minArr = []; const xArr = []
      data.forEach(v => {
        xArr.push(v.classaIndexName)
        dataArr.push(v.avgScore)
        maxArr.push(v.maxScore)
        minArr.push(v.minScore)
      })
      const options = {
        credits: { enabled: false },
        chart: {
          polar: true,
          type: 'line'
        },
        title: {
          text: '',
          x: -80
        },
        plotOptions: {
          line: {
            events: {
              legendItemClick: function(e) {
                return false
              }
            }
          }
        },
        pane: {
          size: '60%'
        },
        xAxis: {
          categories: xArr,
          tickmarkPlacement: 'on',
          lineWidth: 0
        },
        yAxis: {
          gridLineInterpolation: 'polygon',
          lineWidth: 0,
          min: 0,
          max: this.$ldh.max(maxArr),
          tickInterval: this.$ldh.max(maxArr) / 5,
          alternateGridColor: '#f3f3f3'
        },
        tooltip: {
          shared: true,
          useHTML: true,
          pointFormat: '<span style="color:{series.color};font-size:14px">{series.name}: <b>{point.y:,.0f}</b><br/>'
        },
        legend: {
          align: 'center',
          verticalAlign: 'bottom',
          y: 10,
          layout: 'horizontal',
          width: '100%',
          useHTML: true,
          itemDistance: 18,
          labelFormatter() {
            return `<span>${this.name}</span>`
          }
        },
        series: [{
          name: '企业平均得分',
          data: dataArr,
          pointPlacement: 'on',
          color: '#409EFF'
        }, {
          name: '集团最高',
          data: maxArr,
          pointPlacement: 'on',
          color: '#67C23A'
        }, {
          name: '集团最低',
          data: minArr,
          pointPlacement: 'on',
          color: '#F56C6C'
        }]
      }
      if (data.length > 0) {
        this.radarChart = Highcharts.chart('radarChart', options)
      } else {
        this.radarChart = null
        this.layout.chartNoData(this.$refs.radarChart)
      }
      // const indicatorData = []
      // const average = []
      // const maxData = []
      // const minData = []
      // data.map(v => {
      //   average.push(v.avgScore)
      //   maxData.push(v.maxScore || 0)
      //   minData.push(v.minScore || 0)
      //   indicatorData.push({ text: v.classaIndexName, max: 100 })
      // })
      // const params = {
      //   center: ['50%', '45%'],
      //   indicator: indicatorData,
      //   legendBottom: 0,
      //   legend: ['集团平均', '集团最高', '集团最低'],
      //   seriesData: [
      //     {
      //       name: '',
      //       type: 'radar',
      //       data: [{
      //         value: average,
      //         itemStyle: {
      //           color: '#0bf9af'
      //         },
      //         name: '集团平均'
      //       }, {
      //         value: maxData,
      //         itemStyle: {
      //           color: '#00aaff'
      //         },
      //         name: '集团最高'
      //       }, {
      //         value: minData,
      //         itemStyle: {
      //           color: '#ffc200'
      //         },
      //         name: '集团最低'
      //       }]
      //     }
      //   ]
      // }
      // const chart = this.$refs.radarChart
      // if (chart) {
      //   if (data.length > 0) {
      //     const myChart = this.$echarts.init(chart)
      //     myChart.setOption(radarChart(params), true)
      //     window.addEventListener('resize', () => {
      //       myChart.resize()
      //     })
      //   } else {
      //     chart.removeAttribute('_echarts_instance_')
      //     chart.innerHTML = '暂无数据'
      //   }
      // }
    },
    async StatisticsPort() {
      this.layout.showAreaLoading(['#pieChart'])
      const { status, data } = await this.getPort.StatisticsPort({
        scoreTime: this.scoreTime,
        pageNum: 1,
        pageSize: 10,
        companyName: '',
        companyScoreSort: 'desc'
      })
      if (status === 0 && data) {
        this.initPieChart(data)
      }
      this.layout.hideAreaLoading(['#pieChart'])
    },
    initPieChart(data) {
      const totalNum = data.reduce((previousValue, currentValue, currentIndex, array) => previousValue + Number(currentValue.num), 0)
      const colorList = ['#0bf9af', '#00aaff', '#ffc200', '#e74645', '#fb7756', '#facd60', '#fdfa66', '#1ac0c6', '#309975', '#58b368']
      let total = 0
      const dataList = data.map((v, i) => {
        total += v.num
        return {
          value: v.num,
          name: v.key,
          itemStyle: { color: colorList[i] },
          label: {
            color: '#333',
            position: 'outside',
            formatter: (params) => {
              const data = params.data
              if (Number(data.value) === 0) {
                data.labelLine = { show: false }
                data.label.show = false
              } else {
                return `${params.percent}%`
              }
              return `${params.percent}%`
            }
          }
        }
      })
      const dataSeries = [
        {
          name: '集团企业得分情况统计',
          radius: ['50%', '70%'],
          center: ['50%', '48%'],
          data: dataList
        }
      ]
      const params = {
        tooltipShow: true,
        legendShow: false,
        legendBottom: 0,
        titleShow: true,
        fontSize: 14,
        titleText: '总' + total + '个',
        titleX: 'center',
        titleY: 'middle',
        titleColor: '#333',
        tooltipFormatter: (params) => {
          return `${params.seriesName}<br/>${params.marker}${params.name}：${params.value}(${params.percent}%)<br/>`
        }
      }
      const chart = this.$refs.pieChart
      if (chart) {
        if (totalNum !== 0) {
          const myChart = this.$echarts.init(chart)
          myChart.setOption(pieChart(params, dataSeries), true)
          this.setLegend(chart, myChart)
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    },
    async AvgMaxMinScorePort() {
      const { status, data } = await this.getPort.AvgMaxMinScorePort({
        scoreTime: this.scoreTime
      })
      if (status === 0 && data) {
        console.log(data)
        this.scoreObj = data
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.customTimer {
  display: flex;
  align-items: center;
  ::v-deep.timer-title {
    margin: 0;
  }
  ::v-deep.timer-box {
    width: 3.2rem !important;
    border: 1px solid #e9e9e9;
    border-radius: 4px;
  }
}
</style>
<style lang="scss">
.highcharts-label{
  span{
    font-size: 14px!important;
  }
}
</style>
